from django.db import models
from django.contrib.auth.models import User

import time
# Create your models here.

class CheckinLog(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.ForeignKey(User)
    first_login_time = models.TimeField(null=True)
    last_logout_time = models.TimeField(null=True)
    created_date = models.DateTimeField(auto_now_add=True)
    edited_by = models.ForeignKey(User,related_name='edited_by_user_id', null=True)
    
    class Meta:
        db_table = "CHECKIN_LOG"

def update_first_login(user):
    now = time.localtime(time.time())
    rows = CheckinLog.objects.extra(where=[""" user_id = %d and datediff(created_date, '%s') = 0 """ %(user.id, time.strftime('%Y-%m-%d',now))])
    if len(rows) > 0:
        log = rows[0]
        if log.first_login_time == None:
            log.first_login_time = time.strftime('%H:%M:%S',now)
            log.save()

def update_last_logout(user):
    now = time.localtime(time.time())
    rows = CheckinLog.objects.extra(where=[""" user_id = %d and datediff(created_date, '%s') = 0 """ %(user.id, time.strftime('%Y-%m-%d',now))])
    if len(rows) > 0:
        log = rows[0]
        if log.last_logout_time == None:
            log.last_logout_time = time.strftime('%H:%M:%S',now)
            log.save()